<script lang="ts" setup>
import type { Menu } from './data';

import { computed, ref, watch } from 'vue';

import { VIcon } from '@croco/framework/icons';

import { ElMessage } from 'element-plus';

import { getMenuDetails } from '#/api';
import { EditTable } from '#/components/edit-table';
import { IconSelect } from '#/components/icon-select';

import { useDataTemplate, useForm } from './data';

const props = withDefaults(
    defineProps<{
        enums: Record<string, any>;
        menu: Menu;
        save: (data: any) => void;
    }>(),
    {},
);

const menuFormRef = ref();
const treeSelectRef = ref();
const formLoading = ref(false);
const menuTreeData = computed(() => [...props.enums.menu]);
const { buttonDataTemplate } = useDataTemplate();
const { form, datasource, onSubmit, columns, rules } = useForm();

const isUrl = computed(() => (form.value.component ?? '')?.indexOf('http') !== -1 || (form.value.component ?? '')?.includes('{baseUrl}'));

// 菜单发生变化时更新菜单信息并重新加载按钮数据
watch(
    () => props.menu,
    (menu: Menu) => {
        if (menu?.id) {
            formLoading.value = true;
            getMenuDetails(menu.id)
                .then(({ data }) => {
                    if (data.length > 0) {
                        form.value = data[0];
                        datasource.value = data[0].children.filter((item: Menu) => item.type === 'F');
                        if (form.value.parentId === 0) {
                            form.value.parentId = null;
                        }
                        delete form.value.children;
                    } else {
                        form.value = {};
                        datasource.value = [];
                    }
                })
                .finally(() => (formLoading.value = false));
        } else {
            form.value = {};
            datasource.value = [];
        }
    },
);

// 保存菜单
const onSaveMenu = () => {
    menuFormRef.value.validate((valid: any) => {
        if (valid) {
            if (form.value.parentId === props.menu.id) {
                ElMessage.warning(`上级菜单选择错误，不能是移动菜单本身，请选中其他菜单`);
            } else {
                props.save(form.value);
            }
        }
    });
};
</script>

<template>
    <div style="height: 100%; display: flex; justify-content: center" v-if="!form.id">
        <el-empty :image-size="100" description="请选择左侧菜单后操作" />
    </div>
    <el-row v-else :gutter="40" v-loading="formLoading">
        <el-col :lg="24" style="min-height: 335px">
            <div style="display: flex; justify-content: space-between">
                <h2>编辑菜单</h2>
                <div>
                    <el-button @click="() => menuFormRef.resetFields()">
                        <VIcon icon="icon:refresh-left" />
                        恢复默认
                    </el-button>
                    <el-button type="primary" v-auth="'system:menu:edit'" @click="onSaveMenu()" />
                </div>
            </div>
            <el-form ref="menuFormRef" v-if="!formLoading" :model="form" :rules="rules" :label-width="100">
                <el-form-item prop="id" v-show="false">
                    <el-input v-model="form.id" />
                </el-form-item>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="类型" prop="type">
                            <el-select v-model="form.type">
                                <template v-for="(item, index) in enums.type" :key="index">
                                    <el-option v-if="item.value !== 'F'" :label="item.label" :value="item.value" />
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="图标" prop="icon">
                            <IconSelect v-model="form.icon" input />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="显示名称" prop="title">
                            <el-input v-model="form.title" clearable placeholder="显示名字" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="访问路径" prop="path">
                            <el-input v-model="form.path" clearable placeholder="访问路径" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="上级菜单" prop="parentId">
                            <el-tree-select
                                ref="treeSelectRef"
                                v-model="form.parentId"
                                :accordion="true"
                                :check-strictly="true"
                                :data="menuTreeData"
                                :props="{ label: 'title', value: 'id' }"
                                node-key="id"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="授权标识" prop="perms">
                            <el-input v-model="form.perms" clearable placeholder="授权标识" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="路由名称" prop="name">
                            <el-input v-model="form.name" clearable placeholder="路由名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="页面路径" prop="component">
                            <template #label="{ label }">
                                <div class="flex-center">
                                    <span>
                                        {{ label }}
                                    </span>
                                    <el-tooltip
                                        content="如果是内部链接、Iframe直接填写对应URL，{baseUrl}会被替换配置上‘VITE_GLOB_API_URL’的值，例如：https://cn.vitejs.dev/ 或者 {baseUrl}/druid/index.html"
                                    >
                                        <VIcon icon="icon:question-filled" />
                                    </el-tooltip>
                                </div>
                            </template>
                            <el-input v-model="form.component" clearable placeholder="页面路径">
                                <template v-if="form.component && form.component !== 'PageView' && form.component.indexOf('http') !== 0 && !form.component.includes('{baseUrl}')" #suffix>
                                    <el-text type="primary"> /src/view{{ form.component }}.vue</el-text>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="6">
                        <el-form-item label="缓存页面" prop="isCache">
                            <template #label="{ label }">
                                <div class="flex-center">
                                    <span>
                                        {{ label }}
                                    </span>
                                    <el-tooltip content="‘路由名称’需要与Vue页面的defineOptions({name:组件名称})一致才能生效">
                                        <VIcon icon="icon:question-filled" />
                                    </el-tooltip>
                                </div>
                            </template>
                            <el-select v-model="form.isCache">
                                <template v-for="item in enums.choice" :key="item.value">
                                    <el-option :label="item.label" :value="item.value" />
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="内联框架" prop="isFrame">
                            <template #label="{ label }">
                                <div class="flex-center">
                                    <span>
                                        {{ label }}
                                    </span>
                                    <el-tooltip content="需要‘页面路径’是URL才能编辑，如果URL是{baseUrl}开头且开启代理模式，则只能选‘是’">
                                        <VIcon icon="icon:question-filled" />
                                    </el-tooltip>
                                </div>
                            </template>
                            <el-select v-model="form.isFrame" :disabled="!isUrl">
                                <template v-for="item in enums.choice" :key="item.value">
                                    <el-option :label="item.label" :value="item.value" />
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="固定标签" prop="isAffixTab">
                            <el-select v-model="form.isAffixTab">
                                <template v-for="item in enums.choice" :key="item.value">
                                    <el-option :label="item.label" :value="item.value" />
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="菜单可见" prop="visible">
                            <el-select v-model="form.visible">
                                <template v-for="item in enums.choice" :key="item.value">
                                    <el-option :label="item.label" :value="item.value" />
                                </template>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="排序" prop="sequence">
                            <el-input-number v-model="form.sequence" :min="0" controls-position="right" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" clearable placeholder="备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-col>
        <el-col :lg="24" style="height: calc(100% - 945px)">
            <h2>编辑按钮</h2>
            <EditTable
                v-model="datasource"
                :columns="columns"
                :form-template="buttonDataTemplate"
                :submit="onSubmit"
                :auth="{ insert: 'system:menu:add', update: 'system:menu:edit', remove: 'system:menu:remove' }"
                primary-key="id"
                placeholder="暂无匹配相关操作按钮信息"
            >
                <template #icon="scope">
                    <IconSelect v-if="scope.row.editing" v-model="scope.row.icon" />
                    <el-icon v-else>
                        <VIcon :icon="scope.row.icon" />
                    </el-icon>
                </template>
            </EditTable>
        </el-col>
    </el-row>
</template>

<style scoped>
h2 {
    font-size: 18px;
    padding: 0 0 15px 0;
}
</style>
